<?php

namespace app\common\model;

use think\Db;
use think\Exception;
use think\Model;

class Payment extends Model
{
    // 表名
    protected $name = 'payment';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    
    // 追加属性
    protected $append = [
        'status_text',
        'need_password_text',
	    'pay_type_text',
    ];
    
	const STATUS_Y = 1;
	const STATUS_N = 0;
	
	const PASSWORD_Y = 1;
	const PASSWORD_N = 0;
	
	const PAY_TYPE_ALI = 1;
	const PAY_TYPE_WEIXIN = 2;
	const PAY_TYPE_BALANCE = 3;
	const PAY_TYPE_POINT = 4;
//	const PAY_TYPE_OFFLINE = 5;
	public static $_pay_type = [
		self::PAY_TYPE_ALI => '支付宝',
		self::PAY_TYPE_WEIXIN => '微信',
		self::PAY_TYPE_BALANCE => '余额支付',
//		self::PAY_TYPE_OFFLINE => '线下支付'
	];
    
    public function getStatusList()
    {
        return [self::STATUS_Y => '是', self::STATUS_N => '否'];
    }

    public function getNeedPasswordList()
    {
	    return [self::PASSWORD_Y => '是', self::PASSWORD_N=> '否'];
    }

    public static $_types = [
        0 => 'order',
	    1 => 'recharge',
    ];

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : $data['status'];
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getNeedPasswordTextAttr($value, $data)
    {
        $value = $value ? $value : $data['need_password'];
        $list = $this->getNeedPasswordList();
        return isset($list[$value]) ? $list[$value] : '';
    }
	
    public function getPayTypeTextAttr($value, $data) {
	    $value = $value ? $value : $data['pay_type'];
	    $list = self::$_pay_type;
	    return isset($list[$value]) ? $list[$value] : '';
    }
	
	/**
	 * 余额支付订单
	 * @param $orders 支付的订单数据
	 * @param $user 用户数据
	 * @param $orderId 订单ID
	 * @return bool
	 * @throws \think\Exception
	 * @throws \think\exception\PDOException
	 */
    public function balancePayOrder($orders, $user, $orderId) {
	    Db::startTrans();
	    try {
		    $orderModel = new Order();
		    $logModel = new FundsRecord();
			
		    foreach($orders as $order) {
			    //记录扣款记录
			    $logRes = $logModel->addRecord($user['id'], $order['order_amount'],$user['balance'], $logModel::ACCOUNT_TYPE_BALANCE, $logModel::OPE_TYPE_LESS, $logModel::TYPE_PAY_ORDER, $order['id'], '支付订单');
			    if(!$logRes) {
				    throw new Exception('添加资金记录出错');
			    }
			
			    //扣除金额
			    $userRes = Db::name('user')->where(['id' => $user['id']])->setDec('balance', $order['order_amount']);
			    $user['balance'] -= $order['order_amount'];
			    if(!$userRes) {
				    throw new Exception('扣除余额出错');
			    }
			    
			    //扣钱成功后的操作
			    $orderRes = $orderModel->paySuccess($order, self::PAY_TYPE_BALANCE);
			    if(!$orderRes) {
			    	throw new Exception($orderModel->getError());
			    }
		    }
		
		    Db::commit();
		    return true;
	    } catch (Exception $e) {
		    Db::rollback();
		    $this->error = $e->getMessage();
		    return false;
	    }
    }
	
	
	
	/**
	 * 积分支付订单
	 * @param $orders 支付的订单数据
	 * @param $user 用户数据
	 * @param $orderId 订单ID
	 * @return bool
	 * @throws \think\Exception
	 * @throws \think\exception\PDOException
	 */
	public function integralPayOrder($orders, $user, $orderId) {
		Db::startTrans();
		try {
			$orderModel = new Order();
			$logModel = new FundsRecord();
			$supplyModel = new SupplyChain();
			
			foreach($orders as $order) {
				
				//拼团订单支付成功，状态为拼团中
				if($order['order_prom_type'] == Order::ORDER_TYPE_Group) {
					$orderStatus =  $orderModel::STATUS_GROUP_WAIT;
				} else {
					$orderStatus = $orderModel::STATUS_WAIT_DELIVERY;
				}
				
				//更改订单状态
				$orderRes = Db::name('order')->where(['id' => $order['id']])->update([
					'order_status' => $orderStatus,
					'pay_status' => $orderModel::PAY_STATUS_Y,
					'pay_type' => Payment::PAY_TYPE_POINT,
					'pay_time' => time(),
					'update_time' => time(),
				]);
				if(!$orderRes) {
					throw new Exception('更改订单状态出错');
				}
				
				
				//拼团订单支付成功，状态为拼团中
				if($order['order_prom_type'] == Order::ORDER_TYPE_Group) {
					//更改拼团订单数量或开团
					$groupModel = new OrderGroup();
					$goods = Db::name('orderGoods')->where(['order_id' => $order['id']])->find();
					$groupRes = $groupModel->changeNumber($order, $goods['goods_id']);
					if(!$groupRes) {
						throw new Exception($groupModel->getError());
					}
				}
				
				//记录扣款记录
				$logRes = $logModel->addRecord($user['id'], $order['order_amount'],$user['integral'], $logModel::ACCOUNT_TYPE_INTEGRAL, $logModel::OPE_TYPE_LESS, $logModel::TYPE_PAY_ORDER, $order['id'], '支付订单');
				if(!$logRes) {
					throw new Exception('添加资金记录出错');
				}
				
				//扣除积分
				$userRes = Db::name('user')->where(['id' => $user['id']])->setDec('integral', $order['order_amount']);
				$user['integral'] -= $order['order_amount'];
				if(!$userRes) {
					throw new Exception('扣除积分出错');
				}
				
				//添加返利记录
				$rebateRes = $orderModel->addRebateRecord($orderId, $user['id']);
				if(!$rebateRes) {
					throw new Exception($orderModel->getError());
				}
				
				//开通VIP或代理商
				$openRes = $orderModel->openUserGrade($orderId, $user['id']);
				if(!$openRes) {
					throw new Exception($orderModel->getError());
				}
				
				//如果是分期商品订单，添加发货任务
				if($order['order_prom_type'] == Order::ORDER_TYPE_STAGING) {
					$taskModel = new DeliveryTask();
					$taskRes = $taskModel->createTask($order['id'], $order['user_id']);
					if(!$taskRes) {
						throw new Exception('添加分期商品发货任务出错:'.$taskModel->getError());
					}
				}
				
				//如果是押金商品，给押金余额加钱
				if($order['order_prom_type'] == Order::ORDER_TYPE_DEPOSIT && $order['order_amount'] > 0) {
					$depositRes = Db::name('user')
						->where(['id' => $user['id']])
						->setInc('deposit_balance', $order['order_amount']);
					if(!$depositRes) {
						throw new Exception('添加押金金额出错');
					}
					
					//记录流水
					$fundsRes = $logModel->addRecord($user['id'], $order['order_amount'],$user['deposit_balance'], $logModel::ACCOUNT_TYPE_DEPOSIT, $logModel::OPE_TYPE_PLUS, $logModel::TYPE_GOODS_DEPOSIT, $order['id'], '商品押金');
					if(!$fundsRes) {
						throw new Exception('添加押金记录出错');
					}
				}
				
				
				if($order['chain_order_no']) {
					$supplyRes = $supplyModel->payOrder($order['chain_order_no']);
					if(!$supplyRes['status']) {
						throw new Exception($supplyRes['info']);
					}
				}
				
			}
			
			Db::commit();
			return true;
		} catch (Exception $e) {
			Db::rollback();
			$this->error = $e->getMessage();
			return false;
		}
	}
	
}
